import { sqlite } from "./index.js";

// 列表单聊
const personalFields = `
	"id" INTEGER PRIMARY KEY AUTOINCREMENT,
	"username" TEXT,
	"friend_account" TEXT,
	"top_up" INTEGER,
	"friend_phone" TEXT,
  "dialog_id" INTEGER,
	"unread_num" INTEGER,
	"lastMsg" TEXT,
  "isGroup" INTEGER,
  "lastSendTime" TEXT
`

// // 列表群聊
const groupFields = `
  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
  "auto_save" INTEGER,
  "des" TEXT,
  "groupType" INTEGER,
  "group_avatar" TEXT,
  "group_avatar_data" INTEGER,
	"group_id" INTEGER,
	"group_name" TEXT,
  "isGroup" INTEGER,
  "lastMsg" TEXT,
  "lastSendTime" TEXT,
  "projectName" TEXT,
  "top_up" INTEGER,
  "top_up_time" TEXT,
  "unread_num" INTEGER
`

// 对象转字符串
function objectToRawString(input) {
  if (typeof input === 'string') {
    return `'${input.replace(/'/g, "\\'")}'`;
  }
  if (Array.isArray(input)) {
    return `[${input.map(item => objectToRawString(item)).join(',')}]`;
  }
  if (typeof input === 'object' && input !== null) {
    return `{${Object.entries(input).map(([key, val]) => {return `${key}:${objectToRawString(val)}`}).join(',')}}`;
  }
  return String(input);
}

function toSourceLikeString(input) {
  return `${objectToRawString(input)}`;  // 最外层包上双引号
}

// 字符串 => 数组/对象
function safeStringToJson(str) {
  return JSON.parse(
    str
      .replace(/([{,])\s*([a-zA-Z0-9_-]+)\s*:/g, '$1"$2":') // 给 key 加双引号
      .replace(/'([^']*)'/g, '"$1"')                        // 单引号改为双引号
  );
}
let num = 0;
// 清洗聊天列表记录数据
function listSourceToMap (data) {
	const cache = JSON.parse(JSON.stringify(data));
	const { isGroup } = data;
	
	if(cache.lastMsg && cache.lastMsg.content && cache.lastMsg.content.length > 0) {
		cache.lastMsg.content = JSON.parse(cache.lastMsg.content);
		
		let content = cache.lastMsg.content.map(item => {
			item.content = item.content.replace(/(\w+)=["](.*?)["]/g, (match, p1, p2) => {
				// p1 是属性名，p2 是属性值
				return `${p1}='${p2}'`;
			});
			return item
		})
		cache.lastMsg.content = content;
	}
	if(cache.lastMsg && (!cache.lastMsg.content || cache.lastMsg.content.length == 0)) {
		cache.lastMsg.content = [];
	}
	if(data.isGroup == 1) {
		cache.group_avatar_data = cache.group_avatar_data ? JSON.parse(cache.group_avatar_data) : [];
	}
	
	if(data.isGroup == 1) {
		// 对象转纯字符串，sqlite本地无法存储转义字符
		cache.group_avatar_data = toSourceLikeString(cache.group_avatar_data);
	}
	// 对象转纯字符串，sqlite本地无法存储转义字符
	if(cache.lastMsg) {
		cache.lastMsg = toSourceLikeString(cache.lastMsg);
	}
	return cache
}
	 
export const ChatSql = {
	/**
	 * 所有表初始化
	 **/
	createChatTable: function() {
		sqlite.isTable('chat_personal').then(res => {
			if(!res) {
				sqlite.createTab('chat_personal', personalFields);
			}
		});
		
		sqlite.isTable('chat_group').then(res => {
			if(!res) {
				sqlite.createTab('chat_group', groupFields);
			}
		});
	},
	/**
	 * 记录列表
	 **/
	selectList: async function queryChatList(query) {
		const { isGroup, keyword, unreadNum } = query;
		
		const buildWhereClause = (fieldName) => {
			let conditions = [];

			if (keyword) {
				conditions.push(`${fieldName} LIKE '%${keyword}%'`);
			}

			if (unreadNum === 'zero') {
				conditions.push(`unreadNum = 0`);
			} else if (unreadNum === 'gt_zero') {
				conditions.push(`unreadNum > 0`);
			} else if (unreadNum === 'null') {
				conditions.push(`unreadNum IS NULL`);
			}

			return conditions.length ? 'WHERE ' + conditions.join(' AND ') : '';
		};

		try {
			let rows = [];

			if (isGroup === 0) {
				// 单聊
				const where = buildWhereClause('username');
				const sql = `SELECT *, 'personal' AS source FROM chat_personal ${where}`;
				rows = await sqlite.selectBySQL(sql);
			} else if (isGroup === 1) {
				// 群聊
				const where = buildWhereClause('group_name');
				const sql = `SELECT *, 'group' AS source FROM chat_group ${where}`;
				rows = await sqlite.selectBySQL(sql);
			} else {
				// 全查
				const personalWhere = buildWhereClause('username');
				const groupWhere = buildWhereClause('group_name');

				const personalSql = `SELECT *, 'personal' AS source FROM chat_personal ${personalWhere}`;
				const groupSql = `SELECT *, 'group' AS source FROM chat_group ${groupWhere}`;

				const personalList = await sqlite.selectBySQL(personalSql);
				const groupList = await sqlite.selectBySQL(groupSql);

				rows = [...personalList, ...groupList];
			}
			
			rows.forEach(item => {
				if(item.isGroup == 1) {
					item.group_avatar_data = safeStringToJson(item.group_avatar_data);
				}
				if(item.lastMsg) {
					console.log(item)
					item.lastMsg = safeStringToJson(item.lastMsg);
				}
			})
			
			// return [];
			return rows;
		} catch (err) {
			throw err;
		}
	},
	/**
	 * 列表记录添加
	 **/
	addListRecord: function(data){
		if(data.group_name == '发生过感受感受') {
			console.log(listSourceToMap(data))
		}
		
		return sqlite.addTabItem(data.isGroup == 1 ? 'chat_group' : 'chat_personal', listSourceToMap(data));
	},
	/**
	 * 列表记录修改
	 **/
	recordUpdate: function(data) {
		const { isGroup } = data;
		const tableName = isGroup ? 'chat_group' : 'chat_personal';
		const setName = isGroup ? 'group_id' : 'dialog_id';
		const setVal = isGroup ? data.group_id : data.dialog_id;
		
		if(data.group_name == '发生过感受感受') {
			console.log(listSourceToMap(data))
		}
		
		return sqlite.updateSQL(tableName, listSourceToMap(data), setName, setVal);
	},
	/**
	 * 列表记录删除
	 **/
	listDeleteById: function(data){
		const { isGroup } = data;
		const table = isGroup ? 'chat_group' : 'chat_personal';
		const parmas = {};
		if(isGroup) {
			parmas.group_id = data.group_id
		}else {
			parmas.dialog_id = data.dialog_id
		}
		
		return sqlite.deleteInformationType(table, params);
	},
}